package com.shcz.migu.utils;

import android.text.TextUtils;

import com.google.gson.Gson;
import com.shcz.migu.resp.bean.SessionBean;
import com.shcz.migu.resp.bean.UserBean;
import com.shcz.migu.resp.result.LoginResp;

public class UserInforUtils {


    public static void clearData() {
        CommonUtils.addSysMap(Constants.EXTRA_LOGIN_RESULT, "");
    }


    /**
     * @param result
     */
    public static void storeChangedUserInformation(LoginResp.ResultBean result) {
        if (result != null) {
            Gson gson = new Gson();
            CommonUtils.addSysMap(Constants.EXTRA_LOGIN_RESULT, gson.toJson(result));
        }
    }


    public static boolean isShouldLogin() {
        String loginResultString = CommonUtils.getSysMap(Constants.EXTRA_LOGIN_RESULT);
        if (TextUtils.isEmpty(loginResultString)) {
            return true;
        }
        Gson gson = new Gson();
        LoginResp.ResultBean loginRes = gson.fromJson(loginResultString, LoginResp.ResultBean.class);
        String expireTime = loginRes.getSession().getExpire();
        Long expireLong = DateUtil.getMillisecondByDateTime(expireTime, DateUtil.ISO8601DATE_WITH_MILLS_FORMAT);
        return DateUtil.compareDateLong(System.currentTimeMillis(), expireLong);

    }


    public static LoginResp.ResultBean getCurrentLoginResult() {
        String loginResultString = CommonUtils.getSysMap(Constants.EXTRA_LOGIN_RESULT);
        if (loginResultString != null) {
            Gson gson = new Gson();
            return gson.fromJson(loginResultString, LoginResp.ResultBean.class);
        }
        return null;
//        throw new RuntimeException("get current login result failed, Assert!");
    }


    public static SessionBean getSession() {
        return getCurrentLoginResult().getSession();
    }

    public static UserBean getUserBean() {
        return getCurrentLoginResult().getUser();
    }

    public static String getSessionId() {
        String loginResultString = CommonUtils.getSysMap(Constants.EXTRA_LOGIN_RESULT);
        if (TextUtils.isEmpty(loginResultString)) {
            return "";
        }
        if (getSession() == null) {
            return "";
        }
        return getSession().getId();
    }

    public static String getUserId() {
        String loginResultString = CommonUtils.getSysMap(Constants.EXTRA_LOGIN_RESULT);
        if (TextUtils.isEmpty(loginResultString)) {
            return "";
        }
        if (getUserBean() == null) {
            return "";
        }
        return getUserBean().getId() + "";
    }

    public static void setSession(SessionBean result) {
        LoginResp.ResultBean resultBean = getCurrentLoginResult();
        resultBean.setSession(result);
        storeChangedUserInformation(resultBean);
    }
}
